package org.jeecg.modules.product.riskUnit.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.product.riskUnit.entity.TbBaseRiskDevice;
import org.jeecg.modules.product.riskUnit.entity.TbBaseRiskUnit;
import org.jeecg.modules.product.riskUnit.mapper.TbBaseRiskDeviceMapper;
import org.jeecg.modules.product.riskUnit.mapper.TbBaseRiskUnitMapper;
import org.jeecg.modules.product.riskUnit.service.ITbBaseRiskDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 重大危险源装置
 * @Author: jeecg-boot
 * @Date:   2024-04-16
 * @Version: V1.0
 */
@Service
public class TbBaseRiskDeviceServiceImpl extends ServiceImpl<TbBaseRiskDeviceMapper, TbBaseRiskDevice> implements ITbBaseRiskDeviceService {

	@Autowired
	private TbBaseRiskDeviceMapper tbBaseRiskDeviceMapper;
	@Autowired
	private TbBaseRiskUnitMapper tbBaseRiskUnitMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(TbBaseRiskDevice tbBaseRiskDevice, List<TbBaseRiskUnit> tbBaseRiskUnitList) {
		tbBaseRiskDeviceMapper.insert(tbBaseRiskDevice);
		if(tbBaseRiskUnitList!=null && tbBaseRiskUnitList.size()>0) {
			for(TbBaseRiskUnit entity:tbBaseRiskUnitList) {
				//外键设置
				entity.setDeviceId(tbBaseRiskDevice.getId());
				tbBaseRiskUnitMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(TbBaseRiskDevice tbBaseRiskDevice,List<TbBaseRiskUnit> tbBaseRiskUnitList) {
		tbBaseRiskDeviceMapper.updateById(tbBaseRiskDevice);
		
		//1.先删除子表数据
		tbBaseRiskUnitMapper.deleteByMainId(tbBaseRiskDevice.getId());
		
		//2.子表数据重新插入
		if(tbBaseRiskUnitList!=null && tbBaseRiskUnitList.size()>0) {
			for(TbBaseRiskUnit entity:tbBaseRiskUnitList) {
				//外键设置
				entity.setDeviceId(tbBaseRiskDevice.getId());
				tbBaseRiskUnitMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		tbBaseRiskUnitMapper.deleteByMainId(id);
		tbBaseRiskDeviceMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			tbBaseRiskUnitMapper.deleteByMainId(id.toString());
			tbBaseRiskDeviceMapper.deleteById(id);
		}
	}
	
}
